<?php

namespace mbilling\BillingBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;

use mbilling\BillingBundle\Model\OrdersModel;
use mbilling\BillingBundle\Model\OrdersSharedModel;
use mbilling\BillingBundle\Model\UsersModel;
use mbilling\BillingBundle\Model\UsersBillsModel;
use mbilling\BillingBundle\Model\UsersLogsModel;
use mbilling\BillingBundle\Model\OrdersSharedTarifModel;
use mbilling\BillingBundle\Model\DomainsModel;
use mbilling\BillingBundle\Model\OrdersTarifsTermsModel;
use mbilling\BillingBundle\Model\DomainsZonesModel;
use mbilling\BillingBundle\Model\BonusesModel;
use mbilling\BillingBundle\Model\UsersTotalTransactionsModel;
use mbilling\BillingBundle\Model\OrdersSharedMysqlModel;
use mbilling\BillingBundle\Model\OrdersSharedMysqlUsersModel;
use mbilling\BillingBundle\Model\OrdersSharedFtpModel;
use mbilling\BillingBundle\Model\OrdersSharedEmailModel;
use mbilling\BillingBundle\Model\UsersTransactionsModel;
use mbilling\BillingBundle\Model\BonusesTableModel;
use mbilling\BillingBundle\Model\MessagesModel;
use mbilling\BillingBundle\Model\OrdersVpsModel;
use mbilling\BillingBundle\Model\OrdersVpsTarifModel;
use mbilling\BillingBundle\Model\OrdersOSModel;
use mbilling\BillingBundle\Model\OrdersIpModel;
use mbilling\BillingBundle\Model\OrdersIpTableModel;
use mbilling\BillingBundle\Model\DomainsDnsModel;
use mbilling\BillingBundle\Model\TemplatesModel;
use mbilling\BillingBundle\Entity\ordersShared;
use mbilling\BillingBundle\Entity\orders;
use mbilling\BillingBundle\Entity\usersBills;
use mbilling\BillingBundle\Entity\usersLogs;
use mbilling\BillingBundle\Entity\domains;
use mbilling\BillingBundle\Entity\users;
use mbilling\BillingBundle\Entity\usersTotalTransactions;
use mbilling\BillingBundle\Entity\ordersSharedMysql;
use mbilling\BillingBundle\Entity\ordersSharedMysqlUsers;
use mbilling\BillingBundle\Entity\ordersSharedFtp;
use mbilling\BillingBundle\Entity\ordersSharedEmail;
use mbilling\BillingBundle\Entity\usersTransactions;
use mbilling\BillingBundle\Entity\bonusesTable;
use mbilling\BillingBundle\Entity\messages;
use mbilling\BillingBundle\Entity\domainsDns;

use mbilling\BillingBundle\Form\OrdersSharedForm;

use Symfony\Component\Security\Acl\Permission\MaskBuilder;
use mbilling\BillingBundle\Other\GeneratePassword;

class OrdersSharedController extends Controller
{
    public function indexAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();

        
        $orderVps_model = new OrdersVpsModel($em);
        $group_model = new OrdersIpTableModel($em);
        $ip_model = new OrdersIpModel($em);
        $ip_string = array();

        $os_model = new OrdersOSModel($em);
        $os_string = array();

        $domain_model = new DomainsModel($em);
        $domain_string = array();

        $tarif_model = new OrdersVpsTarifModel($em);
        $tarifs = $tarif_model->findAll();
        $tarif_string = array();   
        foreach($tarifs as $tarif)
        {
            $tarif_string[$tarif->getId()]['name'] = $tarif->getName();
            $tarif_string[$tarif->getId()]['cost'] = $tarif->getCost();
        }
        $dns_string = array();
        $gateway_string = array();
        $parameters = array();
        if ($userCurrent == 'anon.')
        {
            return new Response('');
        }
        if ($userCurrent->isAdmin())  
        {
            if ($this->get('session')->get('user'))
                $ordersVps = $orderVps_model->findByUserId($this->get('session')->get('user')->getId());
            else
                $ordersVps = $orderVps_model->findAll();
        }
        else
            $ordersVps = $orderVps_model->findByUserId($userCurrent->getId());

        foreach($ordersVps as $orderVps)
        {
            $ip_string[$orderVps->getId()] = array();
            $ips = $ip_model->findByAccountAndType($orderVps->getName(), 2);
            $dns_string[$orderVps->getId()] = array();
            $gateway_string[$orderVps->getId()] = array();
            $domain_string[$orderVps->getId()] = array();
            foreach($ips as $ip)
            {
                array_push($ip_string[$orderVps->getId()], $ip->getIp());
                $group = $group_model->findByPK($ip->getGroupId());
                array_push($dns_string[$orderVps->getId()], $group->getDns1());
                array_push($dns_string[$orderVps->getId()], $group->getDns2());
                array_push($gateway_string[$orderVps->getId()], $group->getGateway());
            }
            $dns_string[$orderVps->getId()] = array_unique($dns_string[$orderVps->getId()]);
            $gateway_string[$orderVps->getId()] = array_unique($gateway_string[$orderVps->getId()]);
            $os = $os_model->findByPK($orderVps->getOs());
            $os_string[$orderVps->getId()] = $os->getName();

            /*$domains = $domain_model->findByOrderId($orderVps->getOrderId());
            foreach($domains as $domain)
            {
                $temp = array('id' => $domain->getId(), 'name' => $domain->getName());
                array_push($domain_string[$orderVps->getId()], $temp);
            }*/
        }
        $domains = $domain_model->findAll();
        if ($userCurrent->isAdmin()) 
        {
            if ($this->get('session')->get('user'))
                $ordersShared = $orderShared_model->findByUserId($this->get('session')->get('user')->getId());
            else
                $ordersShared = $orderShared_model->findAll();
        }
        else
            $ordersShared = $orderShared_model->findByUserId($userCurrent->getId());
            
        $parameters = array('ordersVps'   => $ordersVps,
                            'ordersShared' => $ordersShared,
                            'tarifs'   => $tarif_string,
                            'ips'      => $ip_string,
                            'os'       => $os_string,
                            'dnss'     => $dns_string,
                            'gateways' => $gateway_string,
                            'domains'  => $domain_string);
        
        if ($userCurrent->isAdmin())
        {
            if ($this->get('session')->get('user'))
            {
                return $this->render('BillingBundle:Orders_shared:user_index.html.twig', array('parameters' => $parameters));
            }
            else
            {
                return $this->render('BillingBundle:Orders_shared:admin_index.html.twig', array('parameters' => $parameters));
            }
        }
        else
        {
            return $this->render('BillingBundle:Orders_shared:user_index.html.twig', array('parameters' => $parameters));
        }
    }
    public function showSummaryAction()
    {
        $order_name = $_POST['order'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $order_model = new OrdersModel($em);
        $tarif_model = new OrdersSharedTarifModel($em);
        $domain_model = new DomainsModel($em);
        $database_model = new OrdersSharedMysqlModel($em);
        $ftp_model = new OrdersSharedFtpModel($em);
        $email_model = new OrdersSharedEmailModel($em);
        
        $order = $order_model->findByOrderName($order_name);
        $domains = $domain_model->findByOrderId($order->getId());
        $databases = $database_model->findByOrderId($order->getId());
        $ftps = $ftp_model->findByOrderId($order->getId());
        $emails = $email_model->findByOrderId($order->getId());
        $orderShared = $orderShared_model->findByOrderId($order->getId());
        
        $tarif = null;
        if (isset($orderShared))
            $tarif = $tarif_model->findByPK($orderShared->getSharedTarif());
        
        $tarifs = $tarif_model->findAll();
        $tarif_string = array();
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        $salt = $tarif->getSalt();
        foreach($tarifs as $tar)
        {
            if (isset($orderShared))
                if ($tar->getId() != $orderShared->getSharedTarif())
                    if (($userCurrent->isAdmin() && !$this->get('session')->get('user')) || $tar->getIsActive())
                    {
                        $id = md5( sha1( $salt.$tar->getId() ));
                        $tarif_string[$id] = $tar;
                    }
                        //$tarif_string[$tar->getId()] = '«'.$tar->getName().'» '.$tar->getHdd().'МБ '.$tar->getSiteCount().' сайта '.$tar->getCost().'Р';
        }

        $c = $order->getCreatedAt();
        $created_at = date_format($c, "d M Y");
        $die_at = date_format($c, "d M Y");
        return $this->render('BillingBundle:Orders_shared:user_index_summary.html.twig', array('order' => $orderShared, 'tarif' => $tarif, 'domains_num' => count($domains), 'mysql_num' => count($databases), 'ftp_num' => count($ftps), 'email_num' => count($emails), 'created_at' => $created_at, 'die_at' => $die_at, 'tarifs' => $tarif_string));
    }
    public function changetarifAction()
    {
        $order_name = $_POST['order'];
        $hash = $_POST['hash'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $order_model = new OrdersModel($em);
        $tarif_model = new OrdersSharedTarifModel($em);

        $order = $order_model->findByOrderName($order_name);
        $orderShared = $orderShared_model->findByOrderId($order->getId());
        $tarif = $tarif_model->findByHash($hash);
        $securityContext = $this->container->get('security.context');
        
        $userCurrent = $securityContext->getToken()->getUser();
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $orderShared_model->update($orderShared, $this->get('session')->get('user'), $tarif, $order);
        else
            $orderShared_model->update($orderShared, $userCurrent, $tarif, $order);
        
        return new Response('true');
    }
    public function extensionAction()
    {
        $order_name = $_POST['order'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        $orderShared_model = new OrdersSharedModel($em);
        $order_model = new OrdersModel($em);
        $transaction_model = new UsersTransactionsModel($em);
        $bonusTable_model = new BonusesTableModel($em);
        $tarif_model = new OrdersSharedTarifModel($em);
        $bonus_model = new BonusesModel($em);
        $domain_model = new DomainsModel($em);
        $zone_model = new DomainsZonesModel($em);
        
        $orders = $order_model->findAll();
        $orders_consum = array();
        $summ = 0;
        foreach($orders as $order)
        {
            $transactions = $transaction_model->findByOrderId($order->getId());
            $order_consum[$order->getId()] = 0;
            foreach($transactions as $transaction)
            {
                if ($transaction->getIsRegular())
                {
                    if ($transaction->getIsAdding())
                    {
                        $order_consum[$order->getId()] -= $transaction->getMoney();
                        $summ -= $transaction->getMoney();
                    }
                    else
                    {
                        $order_consum[$order->getId()] += $transaction->getMoney();
                        $summ += $transaction->getMoney();
                    }
                }
            }
        }
        $order = $order_model->findByOrderName($order_name);
        $orderShared = $orderShared_model->findByOrderId($order->getId());
        $tarif = $tarif_model->findByPK($orderShared->getSharedTarif());
        $tarifs = $tarif_model->findAll();
        $tarif_string = array();
        foreach($tarifs as $tarif)
            $tarif_string[$tarif->getId()] = ' ';

        $domains = $domain_model->findByOrderId($id);
        $domains_ext_cost = array();
        foreach($domains as $domain)
        {
            $zone = $zone_model->findByPK($domain->getZoneId());
            if ($domain->getStatusId() == '1')
                $domains_ext_cost[$domain->getName()] = $zone->getExtCost();
            else
                $domains_ext_cost[$domain->getName()] = '0';
        }
        
        $dir=opendir(dirName('../'.basename(__FILE__)).'/vendor/mpanel/classes/Bonuses/');
        $file_string = array();
        while ($file = readdir($dir))
        {
            if (in_array($file,array('.','..')))
                continue;
            $expl=explode('.', $file);
            $expl_size=sizeof($expl);
            if (mb_strtolower($expl[$expl_size-1],'UTF-8') != 'php')
                continue;
            $file_len = sizeof($file_string);
            $file_string[$file_len] = $file;
        }
        closedir($dir);
        array_multisort($file_string);
        $names = array();
        $coupons = array();
        foreach($file_string as $coupon)
        {
            $expl=explode('.', $coupon);
            $class_name = $expl['0'];
            $class_name = 'Bonuses_'.$class_name;
            $check_domain = $this->get('check_domain');
            $class = $class_name::newInstance(NULL, NULL, NULL, $check_domain, $em);
            array_push($names, $class_name);
            array_push($coupons, $class->getTitle());
        }

        $bonuses = $bonus_model->findAll();
        $coupons_string = array();
        foreach($bonuses as $bonus)
        {
            if ($bonus->getIsActive())
            {
                if ($bonus->getCoupon() != 'no')
                {
                    foreach($names as $key => $name)
                    {
                        if ($name == $bonus->getCoupon())
                            $coupons_string[$bonus->getId()] = $coupons[$key];
                    }
                }
            }
        }

        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $bonusesTable = $bonusTable_model->findByUserIdAndActive($this->get('session')->get('user')->getId(), '1');
        else
            $bonusesTable = $bonusTable_model->findByUserIdAndActive($userCurrent->getId(), '1');
        $bonusesTable_string = array();
        foreach($bonusesTable as $bonusTable)
        {
            $bonus = $bonus_model->findByPK($bonusTable->getBonusId());
            if ($bonus->getCoupon() != 'no')
            {
                foreach($names as $key => $name)
                {
                    if ($name == $bonus->getCoupon())
                        array_push($bonusesTable_string, $coupons[$key]);
                }
            }
        }

        $form = $this->createForm(new OrdersSharedForm($tarif_string), $orderShared);
        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if ($form->isValid())
            {
                return new RedirectResponse($this->generateUrl('shared_show'));
            }
        }
        if ($userCurrent->isAdmin())
        {
            if ($this->get('session')->get('user'))
                return $this->render('BillingBundle:Orders_shared:user_extension.html.twig', array('form' => $form->createView(), 'tarif' => $tarif, 'bonuses' => $bonuses, 'coupons' => $coupons_string, 'order_consum' => $order_consum, 'domains_ext_cost' => $domains_ext_cost, 'bonuses_table' => $bonusesTable_string, 'summ' => $summ));
            else
                return $this->render('BillingBundle:Orders_shared:admin_extension.html.twig', array('form' => $form->createView(), 'tarif' => $tarif, 'bonuses' => $bonuses, 'coupons' => $coupons_string, 'order_consum' => $order_consum, 'domains_ext_cost' => $domains_ext_cost, 'bonuses_table' => $bonusesTable_string, 'summ' => $summ));
        }
        else
            return $this->render('BillingBundle:Orders_shared:user_extension.html.twig', array('form' => $form->createView(), 'tarif' => $tarif, 'bonuses' => $bonuses, 'coupons' => $coupons_string, 'order_consum' => $order_consum, 'domains_ext_cost' => $domains_ext_cost, 'bonuses_table' => $bonusesTable_string, 'summ' => $summ));
    }
    public function showIpsAction()
    {
        $order_name = $_POST['order'];
        $em = $this->get('doctrine.orm.entity_manager');
        $ip_model = new OrdersIpModel($em);
        $order_model = new OrdersModel($em);
        $order = $order_model->findByOrderName($order_name);
        $ips = $ip_model->findByAccountAndType($order_name, 3);
        return $this->render('BillingBundle:Orders_shared:user_index_ips.html.twig', array('order_name' => $order_name, 'ips' => $ips));
    }
    public function createIpsAction()
    {
        $order_name = $_POST['order'];
        $count = $_POST['count'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        
        if ($orderShared->getUnixLogin())
        {
            $tarif_model = new OrdersSharedTarifModel($em);
            $tarif = $tarif_model->findByPK($orderShared->getSharedTarif());
            $bill_model = new UsersBillsModel($em);
            $bill = new usersBills();
            $bill->setMoney($count*$tarif->getAddIpCost());
            $bill->setIsReal('1');
            $bill->setIsPaid('0');
            $bill->setSourceId('0');
            $securityContext = $this->container->get('security.context');
            $userCurrent = $securityContext->getToken()->getUser();
            if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                $bill->setUserId($this->get('session')->get('user')->getId());
            else
                $bill->setUserId($userCurrent->getId());
            $bill->setCurrencyId('1');
            $bill->setOrderId($orderShared->getOrderId());
            $bill->setType('7');
            $bill->setPeriod($count);
            $bill_model->create($bill);
            return new Response('true');
            //return new RedirectResponse($this->generateUrl('users_bills_show'));
        }
        return new Response('false');
    }
    public function showDomainsAction()
    {
        $order_name = $_POST['order'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $domain_model = new DomainsModel($em);
        $order_model = new OrdersModel($em);
        $order = $order_model->findByOrderName($order_name);
        $domains = $domain_model->findByOrderId($order->getId());
        $this->get('session')->set('order', $order_name);
        
        return $this->render('BillingBundle:Orders_shared:user_index_domains.html.twig', array('order_name' => $order_name, 'domains' => $domains));
    }
    public function synchDomainsAction()
    {
        
    }
    public function showDnsAction()
    {
        $order_name = $_POST['order'];
        $domain_name = $_POST['domain'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $domain_model = new DomainsModel($em);
        $domainDns_model = new DomainsDnsModel($em);
        $order_model = new OrdersModel($em);
        $order = $order_model->findByOrderName($order_name);
        $domain = $domain_model->findByDomainName($domain_name);
        $domainsDns = $domainDns_model->findByDomainId($domain->getId());
        $dns_hashs = array();
        foreach($domainsDns as $domainDns)
        {
            $dns_hashs[$domainDns->getId()] = md5($domainDns->getName().$domainDns->getType().$domainDns->getValue().$domain_name);
        }
        //print_r($dns_hashs);
        return $this->render('BillingBundle:Orders_shared:user_index_domainsDns.html.twig', array('order_name' => $order_name,'domain' => $domain,'domainsDns' => $domainsDns, 'dns_hashs' => $dns_hashs));
    }
    public function createDnsAction()
    {
        $order_name = $_POST['order'];
        $domain_name = $_POST['domain'];
        $name = $_POST['name'];
        $type = $_POST['type'];
        $value = $_POST['value'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        
        $jabber = $this->get('jabber');
        if (!$jabber->check())
            return new Response('jabber error');
        if ($orderShared->getUnixLogin())
        {
            $domain_model = new DomainsModel($em);
            $domainDns_model = new DomainsDnsModel($em);
            $domain = $domain_model->findByDomainName($domain_name);
            $check_domain = $this->get('check_domain');
            $check_domain->init($domain_name);
            $id = $jabber->sendMessage(29, array('domain' => '"'.$orderShared->getUnixLogin().'|'.$check_domain->getDomain().'"', 'name' => '"'.$name.'"', 'type' => '"'.$type.'"', 'value' => '"'.$value.'"'));
            
            $dns = new domainsDns();
            $dns->setName($name);
            $dns->setType($type);
            $dns->setValue($value);
            $dns->setDomainId($domain->getId());
            $dns->setIsActive("0");
            $dns->setForRemove("0");
            $dns->setMessageId($id);
            $domainDns_model->create($dns);    
        }
        return new Response('true');
    }
    public function removeDnsAction()
    {
        $order_name = $_POST['order'];
        $hash = $_POST['hash'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        
        $jabber = $this->get('jabber');
        if (!$jabber->check())
            return new Response('jabber error');
        if ($orderShared->getUnixLogin())
        {
            $domainDns_model = new DomainsDnsModel($em);
            $dns = $domainDns_model->findByHash($hash);
            $domain_model = new DomainsModel($em);
            $domain = $domain_model->findByPK($dns->getDomainId());
            
            $check_domain = $this->get('check_domain');
            $check_domain->init($domain->getName());
            $id = $jabber->sendMessage(30, array('domain' => '"'.$orderShared->getUnixLogin().'|'.$check_domain->getDomain().'"', 'name' => '"'.$dns->getName().'"', 'type' => '"'.$dns->getType().'"', 'value' => '"'.$dns->getValue().'"'));
            
            $dns->setIsActive("0");
            $dns->setForRemove("1");
            $dns->setMessageId($id);
            $domainDns_model->create($dns);    
        }
        return new Response('true');
    }
    public function changeDnsAction()
    {
        $order_name = $_POST['order'];
        $hash = $_POST['hash'];
        $name = $_POST['name'];
        $type = $_POST['type'];
        $value = $_POST['value'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        
        $jabber = $this->get('jabber');
        if (!$jabber->check())
            return new Response('jabber error');
        if ($orderShared->getUnixLogin())
        {
            $domainDns_model = new DomainsDnsModel($em);
            $dns = $domainDns_model->findByHash($hash);
            $domain_model = new DomainsModel($em);
            $domain = $domain_model->findByPK($dns->getDomainId());
            
            $check_domain = $this->get('check_domain');
            $check_domain->init($domain->getName());
            $source = '"'.$dns->getName().' '.$dns->getType().' '.$dns->getValue().'"';
            $dest = '"'.$name.' '.$type.' '.$value.'"';
            $id = $jabber->sendMessage(31, array('domain' => '"'.$orderShared->getUnixLogin().'|'.$check_domain->getDomain().'"', 'source' => $source, 'dest' => $dest));
            
            $dns->setIsActive("0");
            $dns->setMessageId($id);
            $domainDns_model->create($dns);    
        }
        return new Response('true');
    }
    public function synchDnsAction()
    {
        $order_name = $_POST['order'];
        $domain_name = $_POST['domain'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $domainDns_model = new DomainsDnsModel($em);
        $domain_model = new DomainsModel($em);
        $orderShared_model = new OrdersSharedModel($em);

        $jabber = $this->get('jabber');
        if (!$jabber->check())
            return new Response('jabber error');
        $orderShared = $orderShared_model->findByOrderName($order_name);
        if ($orderShared->getUnixLogin())
        {
            $domain = $domain_model->findByDomainName($domain_name);
            $dnss = $domainDns_model->findByDomainId($domain->getId());
            $id = $jabber->sendMessage(32, array('domain' => '"'.$domain_name.'"'));
            $str = $jabber->waitMessage($id); 
            $dns_records = array();
            
            if (array_key_exists('error', $str))
                return new Response($str['error']);
            
            foreach($str as $s)
            {
                $pars = explode("\t", $s);
                array_push($dns_records, $pars);
            }
            
            foreach($dnss as $dns)
            {
                if ($dns->getIsActive() == "1")
                    $domainDns_model->removeByPK($dns->getId());
            }
            foreach($dns_records as $pars)
            {
                $name = $pars['0'];
                $type = $pars['3'];
                $value = $pars['4'];
                
                $hash = md5($name.$type.$value.$domain_name);
                $dns = $domainDns_model->findByHash($hash);
                if (isset($dns))
                    continue;
                $dns = new domainsDns();
                $dns->setName($name);
                $dns->setType($type);
                $dns->setValue($value);
                $dns->setDomainId($domain->getId());
                $dns->setIsActive("1");
                $dns->setForRemove("0");
                $domainDns_model->create($dns);
            }
        }
        return new Response('true');
    }
    public function showDatabasesAction()
    {
        $order_name = $_POST['order'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $database_model = new OrdersSharedMysqlModel($em);
        $databaseUser_model = new OrdersSharedMysqlUsersModel($em);
        $order_model = new OrdersModel($em);
        $order = $order_model->findByOrderName($order_name);
        $databases = $database_model->findByOrderId($order->getId());
        $databases_users = array();
        $rights = array();
        foreach($databases as $database)
        {
            $databases_users[$database->getId()]['database'] = $database;
            $databases_users[$database->getId()]['users'] = array();
            $users = $databaseUser_model->findByBaseId($database->getId());
            foreach($users as $user)
            {
                array_push($databases_users[$database->getId()]['users'], $user);
                $rights[$user->getId()] = $user->getUserRightsArray();
            }
        }

        return $this->render('BillingBundle:Orders_shared:user_index_databases.html.twig', array('databases_users' => $databases_users, 'order_name' => $order_name, 'rights' => $rights));
    }
    public function createDatabaseAction()
    {
        $order_name = $_POST['order'];
        $base_name = $_POST['base'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        
        $jabber = $this->get('jabber');
        if (!$jabber->check())
            return new Response('jabber error');
        if ($orderShared->getUnixLogin())
        {
            $database_model = new OrdersSharedMysqlModel($em);
            $order_model = new OrdersModel($em);
            $order = $order_model->findByOrderName($order_name);

            $id = $jabber->sendMessage(12, array('name' => '"'.$orderShared->getUnixLogin().'_'.$base_name.'"'));
            
            $database = new ordersSharedMysql();
            $database->setName($base_name);
            $database->setOrderId($order->getId());
            $database->setIsActive("0");
            $database->setForRemove("0");
            $database->setMessageId($id);
            $database_model->create($database);    
        }
        return new Response('true');
    }
    public function removeDatabaseAction()
    {
        $order_name = $_POST['order'];
        $base_name = $_POST['base'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        $database_model = new OrdersSharedMysqlModel($em);
        $database = $database_model->FindByBaseNameAndOrderId($base_name, $orderShared->getOrderId());

        $jabber = $this->get('jabber');
        if (!$jabber->check())
            return new Response('jabber error');
        if ($orderShared->getUnixLogin())
        {
            $databaseUser_model = new OrdersSharedMysqlUsersModel($em);
            $users = $databaseUser_model->findByBaseId($database->getId());
            foreach ($users as $user)
            {
                $id = $jabber->sendMessage(15, array('login' => '"'.$orderShared->getUnixLogin().'_'.$user->getLogin().'"', 
                                                     'name'  => '"'.$orderShared->getUnixLogin().'_'.$base_name.'"'));
                $user->setIsActive("0");
                $user->setForRemove("1");
                $user->setMessageId($id);
                $databaseUser_model->create($user);
                //$databaseUser_model->removeByPK($user->getId());
            }
            $params = array('name' => $orderShared->getUnixLogin().'_'.$database->getName());
            $id = $jabber->sendMessage(18, $params);
            $database->setIsActive("0");
            $database->setForRemove("1");
            $database->setMessageId($id);
            $database_model->create($database);
            //$database_model->removeByPK($database->getId());   
        }
        return new Response('true');
        /*$conn = $em->getConnection();
        $sm = $conn->getSchemaManager();
        $sm->dropDatabase($database->getName());*/
    }
    public function createDatabaseUserAction()
    {
        $order_name = $_POST['order'];
        $base_name = $_POST['base'];
        $login = $_POST['user'];
        $password = $_POST['password'];
        $password = base64_encode($password);
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        $database_model = new OrdersSharedMysqlModel($em);
        $database = $database_model->FindByBaseNameAndOrderId($base_name, $orderShared->getOrderId());

        $jabber = $this->get('jabber');
        if (!$jabber->check())
            return new Response('jabber error');
        if ($orderShared->getUnixLogin())
        {
            $rights = 'All';
            $params = array('rights' => '"'.$rights.'"', 'name' => '"'.$orderShared->getUnixLogin().'_'.$database->getName().'"', 'login' => '"'.$orderShared->getUnixLogin().'_'.$login.'"', 'password' => '"'.$password.'"');
            $id = $jabber->sendMessage(10, $params);
            
            $databaseUser_model = new OrdersSharedMysqlUsersModel($em);
            $user = new ordersSharedMysqlUsers();
            $user->setBaseId($database->getId());
            $user->setLogin($login);
            $user->setHost('localhost');
            $user->setRights('Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y');;
            $user->setIsActive("0");
            $user->setForRemove("0");
            $user->setMessageId($id);
            $databaseUser_model->create($user);
        }
        return new Response('true');
    }
    public function removeDatabaseUserAction()
    {
        $order_name = $_POST['order'];
        $base_name = $_POST['base'];
        $login = $_POST['user'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        $database_model = new OrdersSharedMysqlModel($em);
        $database = $database_model->FindByBaseNameAndOrderId($base_name, $orderShared->getOrderId());
        
        $jabber = $this->get('jabber');
        if (!$jabber->check())
            return new Response('jabber error');
        if ($orderShared->getUnixLogin())
        {
            $params = array('login' => '"'.$orderShared->getUnixLogin().'_'.$login.'"', 'name' => '"'.$orderShared->getUnixLogin().'_'.$database->getName().'"');
            $id = $jabber->sendMessage(15, $params);
            
            $databaseUser_model = new OrdersSharedMysqlUsersModel($em);
            $user = $databaseUser_model->findByBaseIdAndLogin($database->getId(), $login);
            $user->setIsActive("0");
            $user->setForRemove("1");
            $user->setMessageId($id);
            $databaseUser_model->create($user);
            //$databaseUser_model->removeByPK($user->getId());
        }
        return new Response('true');
    }
    public function changeDatabaseUserPasswordAction()
    {
        $order_name = $_POST['order'];
        $base_name = $_POST['base'];
        $login = $_POST['user'];
        $password = $_POST['password'];
        $password = base64_encode($password);
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        $database_model = new OrdersSharedMysqlModel($em);
        $database = $database_model->FindByBaseNameAndOrderId($base_name, $orderShared->getOrderId());
        
        $jabber = $this->get('jabber');
        if (!$jabber->check())
            return new Response('jabber error');
        if ($orderShared->getUnixLogin())
        {
            $params = array('name' => '"'.$orderShared->getUnixLogin().'_'.$database->getName().'"', 'login' => '"'.$orderShared->getUnixLogin().'_'.$login.'"', 'password' => '"'.$password.'"');
            $id = $jabber->sendMessage(23, $params);
            
            $databaseUser_model = new OrdersSharedMysqlUsersModel($em);
            $user = $databaseUser_model->findByBaseIdAndLogin($database->getId(), $login);
            $user->setIsActive("0");
            $user->setMessageId($id);
            $databaseUser_model->create($user);
        }
        return new Response('true');
    }
    public function changeDatabaseUserRightsAction()
    {
        $order_name = $_POST['order'];
        $base_name = $_POST['base'];
        $login = $_POST['user'];
        $rights = $_POST['rights'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        $database_model = new OrdersSharedMysqlModel($em);
        $database = $database_model->FindByBaseNameAndOrderId($base_name, $orderShared->getOrderId());
        
        $jabber = $this->get('jabber');
        if (!$jabber->check())
            return new Response('jabber error');
        if ($orderShared->getUnixLogin())
        {
            $rights_array = explode('_', $rights);
            $mysql_rights = array('SELECT', 'INSERT', 'UPDATE', 'DELETE', 
                                  'CREATE', 'DROP', 'REFERENCES',
                                  'INDEX', 'ALTER', 'CREATE TEMPORARY TABLES', 'LOCK TABLES', 
                                  'CREATE VIEW', 'SHOW VIEW', 'CREATE ROUTINE', 'ALTER ROUTINE', 
                                  'EXECUTE', 'EVENT', 'TRIGGER');
            //$rights_str = "\'";
            $rights_str = "";
            foreach($rights_array as $key => $right)
            {
                if ($right == "Y")
                {
                    if ($rights_str != "")
                        $rights_str .= ',';
                    $rights_str .= $mysql_rights[$key];
                }
            }
            //$rights_str .= "\'";

            $params = array('name' => '"'.$orderShared->getUnixLogin().'_'.$database->getName().'"', 'login' => '"'.$orderShared->getUnixLogin().'_'.$login.'"', 'rights' => '"'.$rights_str.'"');
            $id = $jabber->sendMessage(24, $params);
            
            $databaseUser_model = new OrdersSharedMysqlUsersModel($em);
            $user = $databaseUser_model->findByBaseIdAndLogin($database->getId(), $login);
            $user->setIsActive("0");
            $rights = str_replace("_", " ", $rights);
            $user->setRights($rights);
            $user->setMessageId($id);
            $databaseUser_model->create($user);
        }
        return new Response('true');
    }
    public function synchDatabaseAction()
    {
        $order_name = $_POST['order'];

        $em = $this->get('doctrine.orm.entity_manager');
        $database_model = new OrdersSharedMysqlModel($em);
        $databaseUser_model = new OrdersSharedMysqlUsersModel($em);
        $orderShared_model = new OrdersSharedModel($em);

        $jabber = $this->get('jabber');
        if (!$jabber->check())
            return new Response('jabber error');
        $orderShared = $orderShared_model->findByOrderName($order_name);
        if ($orderShared->getUnixLogin())
        {
            $id = $jabber->sendMessage(14, array('prefix' => '"'.$orderShared->getUnixLogin().'"'));
            $database_users = $jabber->waitMessage($id);

            if (array_key_exists('error', $database_users))
                return new Response($database_users['error']);
            //return new Response('true');
            $databases = $database_model->findByOrderId($orderShared->getOrderId());
            foreach ($databases as $database)
            {
                if ($database->getIsActive() == "1")
                {
                    $users = $databaseUser_model->findByBaseId($database->getId());
                    $is_active = 1;
                    foreach ($users as $user)
                    {
                        if ($user->getIsActive() == "1")
                            $databaseUser_model->removeByPK($user->getId());
                        else
                            $is_active = 0;
                    }
                    if ($is_active)
                        $database_model->removeByPK($database->getId());
                }
            }
            
            $databases = array();
            foreach($database_users as $key => $item)
            {
                $temp = explode("\t", $item);
                $base_name = preg_replace("/(.)*_/", '', $temp['0']);
                if (!array_key_exists($base_name, $databases))
                    $databases[$base_name] = array();
                if (array_key_exists('1', $temp))
                {
                    $host = preg_replace("/(.)*_/", '', $temp['1']);
                    $user_name = preg_replace("/(.)*_/", '', $temp['3']); 
                    if (!array_key_exists($user_name, $databases[$base_name]))
                        $databases[$base_name][$user_name] = array();
                    $rights = array();
                    for ($i = 4; $i <= 22; $i++)
                        array_push($rights, $temp[$i]);
                    $databases[$base_name][$user_name]['rights'] =  $rights;
                    $databases[$base_name][$user_name]['host'] =  $host;
                }
            }
            //print_r($databases);
            foreach($databases as $db_name => $database)
            {
                $db = $database_model->findByBaseNameAndOrderId($db_name, $orderShared->getOrderId());
                if (!isset($db))
                {
                    $db = new ordersSharedMysql();
                    $db->setName($db_name);
                    $db->setIsActive("1");
                    $db->setForRemove("0");
                    $db->setOrderId($orderShared->getOrderId());
                    $database_model->create($db);
                }
                foreach($database as $login => $item)
                {
                    $user = $databaseUser_model->findByBaseIdAndLogin($db->getId(), $login);
                    if (isset($user))
                        continue;
                    $user = new ordersSharedMysqlUsers();
                    $user->setBaseId($db->getId());
                    $user->setLogin($login);
                    $user->setHost($item['host']);
                    $rights_string = '';
                    foreach($item['rights'] as $key => $right)
                    {
                        if ($key != 6)
                            $rights_string .= $right.' ';
                    }
                    $user->setRights($rights_string);
                    $user->setIsActive("1");
                    $user->setForRemove("0");
                    $databaseUser_model->create($user);
                }
            }
        }
        return new Response('true');
    }
    /*function cmp($email1, $email1)
    {
        if ($email1.getLogin() == $email2.getLogin()) 
            return 0;
        return ($email1.getLogin() < $email2.getLogin()) ? -1 : 1;
    }*/
    public function showEmailAction()
    {
        $order_name = $_POST['order'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $email_model = new OrdersSharedEmailModel($em);
        $domain_model = new DomainsModel($em);
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        $domains = $domain_model->findByOrderId($orderShared->getOrderId());
        $emails = $email_model->findByOrderId($orderShared->getOrderId());
        $emails_domains = array();
        /*foreach($emails as $email)
        {
            $domain = $domain_model->FindByPK($email->getDomainId());
            if (!array_key_exists($domain->getId(), $emails_domains))
            {
                $emails_domains[$domain->getId()]['domain'] = $domain->getName();
                $emails_domains[$domain->getId()]['emails'] = array();
            }
            array_push($emails_domains[$domain->getId()]['emails'], $email);
        }*/
        foreach($domains as $domain)
        {
            if (!array_key_exists($domain->getId(), $emails_domains))
            {
                $emails_domains[$domain->getId()]['domain'] = $domain->getName();
                //$emails_domains[$domain->getId()]['emails'] = array();
            }
            $emails = $email_model->findByDomainId($domain->getId());
            $emails_domains[$domain->getId()]['emails'] = $emails;
        }
        sort($emails_domains);

        return $this->render('BillingBundle:Orders_shared:user_index_emails.html.twig', array('emails_domains' => $emails_domains, 'order_name' => $order_name, 'domains' => $domains));
    }
    public function createEmailAction()
    {
        $order_name = $_POST['order'];
        $domain_name = $_POST['domain'];
        $user = $_POST['user'];
        $password = $_POST['password'];
        $password = base64_encode($password);
        
        $em = $this->get('doctrine.orm.entity_manager');
        $domain_model = new DomainsModel($em);
        $domain = $domain_model->FindByDomainName($domain_name); 
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        
        $jabber = $this->get('jabber');
        if (!$jabber->check())
            return new Response('jabber error');
        if ($orderShared->getUnixLogin())
        {
            $check_domain = $this->get('check_domain');
            $check_domain->init($domain_name);
            $params = array('user' => '"'.$orderShared->getUnixLogin().'"', 'email' => '"'.$user.'@'.$check_domain->getDomain().'"', 'password' => '"'.$password.'"');
            $id = $jabber->sendMessage(20, $params);
            
            $email_model = new OrdersSharedEmailModel($em);
            $email = new ordersSharedEmail();
            $email->setUser($user);
            $email->setDomainId($domain->getId());
            $email->setOrderId($orderShared->getOrderId());
            $email->setIsActive("0");
            $email->setForRemove("0");
            $email->setMessageId($id);
            $email_model->create($email);    
        }
        return new Response('true');
    }
    public function removeEmailAction()
    {
        $order_name = $_POST['order'];
        $email_name = $_POST['email'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        $email_model = new OrdersSharedEmailModel($em);
        $result = explode("@", $email_name);
        $email = $email_model->findByUserAndDomainAndOrderId($result['0'], $result['1'], $orderShared->getOrderId());

        $jabber = $this->get('jabber');
        if (!$jabber->check())
            return new Response('jabber error');
        if ($orderShared->getUnixLogin())
        {
            $domain_model = new DomainsModel($em);
            $domain = $domain_model->FindByPK($email->getDomainId());
            
            $check_domain = $this->get('check_domain');
            $check_domain->init($domain->getName());
            $params = array('user' => '"'.$orderShared->getUnixLogin().'"', 'email' => '"'.$email->getUser().'@'.$check_domain->getDomain().'"');
            $id = $jabber->sendMessage(21, $params);
            $email->setIsActive("0");
            $email->setForRemove("1");
            $email->setMessageId($id);
            $email_model->create($email);        
        }
        return new Response('true');
    }
    public function changeEmailAction()
    {
        $order_name = $_POST['order'];
        $email_name = $_POST['email'];
        $password = $_POST['password'];
        $password = base64_encode($password);
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        $email_model = new OrdersSharedEmailModel($em);
        $result = explode("@", $email_name);
        $email = $email_model->findByUserAndDomainAndOrderId($result['0'], $result['1'], $orderShared->getOrderId());
        
        $jabber = $this->get('jabber');
        if (!$jabber->check())
            return new Response('jabber error');
        if ($orderShared->getUnixLogin())
        {
            $domain_model = new DomainsModel($em);
            $domain = $domain_model->FindByPK($email->getDomainId());
            
            $check_domain = $this->get('check_domain');
            $check_domain->init($domain->getName());
            $params = array('user' => '"'.$orderShared->getUnixLogin().'"', 'password' => '"'.$password.'"', 'email' => '"'.$email->getUser().'@'.$check_domain->getDomain().'"');
            $id = $jabber->sendMessage(22, $params);
            $email->setIsActive("0");
            $email->setForRemove("0");
            $email->setMessageId($id);
            $email_model->create($email);
        }
        return new Response('true');
    }
    public function synchEmailAction()
    {
        $order_name = $_POST['order'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $email_model = new OrdersSharedEmailModel($em);
        $domain_model = new DomainsModel($em);
        $orderShared_model = new OrdersSharedModel($em);

        $jabber = $this->get('jabber');
        if (!$jabber->check())
            return new Response('jabber error');
        $orderShared = $orderShared_model->findByOrderName($order_name);
        if ($orderShared->getUnixLogin())
        {
            $emails = $email_model->findByOrderId($orderShared->getOrderId());
            $domains = $domain_model->findByOrderId($orderShared->getOrderId());
            $domain_users = array();
            $id = $jabber->sendMessage(19, array('user' => '"'.$orderShared->getUnixLogin().'"'));
            $str = $jabber->waitMessage($id); 

            if (array_key_exists('error', $str))
                return new Response($str['error']);
            
            foreach($str as $s)
            {
                $users = explode("\t", $s);
                if (!array_key_exists($users['0'], $domain_users))
                {
                    $domain_users[$users['0']] = array();
                    for($i = 1; $i < count($users); $i++)
                        array_push($domain_users[$users['0']], $users[$i]);
                }
            }

            $check_domain = $this->get('check_domain');
            foreach($domain_users as $domain_name => $users)
            {
                foreach($users as $user)
                {
                    $check_domain->init($domain_name);
                    $name = $check_domain->convertFromPunycode($domain_name);
                    if (!$domain_model->checkDomain($name))
                        return new Response('domain '.$name.' does not exist');
                }
            }
            foreach($emails as $email)
            {
                if ($email->getIsActive() == "1")
                    $email_model->removeByPK($email->getId());
            }
            foreach($domain_users as $domain_name => $users)
            {
                foreach($users as $user)
                {
                    $check_domain->init($domain_name);
                    $name = $check_domain->convertFromPunycode($domain_name);
                    $domain = $domain_model->FindByDomainName($name);
                    $email = $email_model->findByUserAndDomainAndOrderId($user, $name, $orderShared->getOrderId());
                    if (isset($email))
                        continue;
                    $email = new ordersSharedEmail();
                    $email->setUser($user);
                    $email->setDomainId($domain->getId());
                    $email->setOrderId($orderShared->getOrderId());
                    $email->setIsActive("1");
                    $email->setForRemove("0");
                    //$email->setMessageId($id);
                    $email_model->create($email);
                }
            }
        }
        return new Response('true');
    }
    public function showFTPAction()
    {
        $order_name = $_POST['order'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $ftp_model = new OrdersSharedFtpModel($em);
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        $ftps = $ftp_model->findByOrderId($orderShared->getOrderId());
        return $this->render('BillingBundle:Orders_shared:user_index_ftps.html.twig', array('ftps' => $ftps, 'order_name' => $order_name));
    }
    public function createFTPAction()
    {
        $order_name = $_POST['order'];
        $user = $_POST['user'];
        $password = $_POST['password'];
        $password = base64_encode($password);
        $dir = $_POST['dir'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        
        $jabber = $this->get('jabber');
        if (!$jabber->check())
            return new Response('jabber error');
        if ($orderShared->getUnixLogin())
        {
            $params = array('full_login' => '"'.$user.'@'.$orderShared->getUnixLogin().'"', 'password' => '"'.$password.'"', 'dir' => '"'.$dir.'"');
            $id = $jabber->sendMessage(25, $params);
            
            $ftp_model = new OrdersSharedFtpModel($em);
            $ftp = new ordersSharedFtp();
            $ftp->setUser($user);
            $ftp->setDir($dir);
            $ftp->setOrderId($orderShared->getOrderId());
            $ftp->setIsActive("0");
            $ftp->setForRemove("0");
            $ftp->setMessageId($id);
            $ftp_model->create($ftp);
        }
        return new Response('true');
    }
    public function removeFTPAction()
    {
        $order_name = $_POST['order'];
        $user = $_POST['user'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        $ftp_model = new OrdersSharedFtpModel($em);
        $ftp = $ftp_model->findByUserAndOrderId($user, $orderShared->getOrderId());
        
        $jabber = $this->get('jabber');
        if (!$jabber->check())
            return new Response('jabber error');
        if ($orderShared->getUnixLogin())
        {
            $params = array('full_login' => '"'.$user.'@'.$orderShared->getUnixLogin().'"');
            $id = $jabber->sendMessage(26, $params);
            $ftp->setIsActive("0");
            $ftp->setForRemove("1");
            $ftp->setMessageId($id);
            $ftp_model->create($ftp);
        }
        return new Response('true');
    }
    public function changeFTPAction()
    {
        $order_name = $_POST['order'];
        $user = $_POST['user'];
        $password = $_POST['password'];
        $password = base64_encode($password);
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        $ftp_model = new OrdersSharedFtpModel($em);
        $ftp = $ftp_model->findByUserAndOrderId($user, $orderShared->getOrderId());
        
        $jabber = $this->get('jabber');
        if (!$jabber->check())
            return new Response('jabber error');
        if ($orderShared->getUnixLogin())
        {
            $params = array('full_login' => '"'.$user.'@'.$orderShared->getUnixLogin().'"', 'password' => '"'.$password.'"');
            $id = $jabber->sendMessage(27, $params);
            $ftp->setIsActive("0");
            $ftp->setForRemove("0");
            $ftp->setMessageId($id);
            $ftp_model->create($ftp);
        }
        return new Response('true');
    }
    public function synchFTPAction()
    {
        $order_name = $_POST['order'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $ftp_model = new OrdersSharedFtpModel($em);
        $orderShared_model = new OrdersSharedModel($em);

        $jabber = $this->get('jabber');
        if (!$jabber->check())
            return new Response('jabber error');
        $orderShared = $orderShared_model->findByOrderName($order_name);
        if ($orderShared->getUnixLogin())
        {
            $ftps = $ftp_model->findByOrderId($orderShared->getOrderId());
            $id = $jabber->sendMessage(28, array('user' => '"'.$orderShared->getUnixLogin().'"'));
            $str = $jabber->waitMessage($id); 
            $ftp_users = array();
            
            if (array_key_exists('error', $str))
                return new Response($str['error']);
            
            foreach($str as $s)
            {
                $pars = explode("\t", $s);
                if (!array_key_exists($pars['0'], $pars ))
                {
                    $ftp_users[$pars['0']] = $pars;
                }
            }

            foreach($ftps as $ftp)
            {
                if ($ftp->getIsActive() == "1")
                    $ftp_model->removeByPK($ftp->getId());
            }
            foreach($ftp_users as $pars)
            {
                $temp = explode("@", $pars['0']);
                $user = $temp['0'];
                $ftp = $ftp_model->findByUserAndOrderId($user, $orderShared->getOrderId());
                if (isset($ftp))
                    continue;
                $ftp = new ordersSharedFtp();
                $ftp->setUser($user);
                $ftp->setDir($pars['2']);
                $ftp->setOrderId($orderShared->getOrderId());
                $ftp->setIsActive("1");
                $ftp->setForRemove("0");
                //$email->setMessageId($id);
                $ftp_model->create($ftp);
            }
        }      
        return new Response('true');
    }
    public function updateInfoAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $jabber = $this->get('jabber');
        if (!$jabber->check())
            return new Response('true');
        $database_model = new OrdersSharedMysqlModel($em);
        $databaseUser_model = new OrdersSharedMysqlUsersModel($em);
        $email_model = new OrdersSharedEmailModel($em);
        $ftp_model = new OrdersSharedFtpModel($em);
        $dns_model = new DomainsDnsModel($em);
        $orderShared_model = new OrdersSharedModel($em);
        $domain_model = new DomainsModel($em);
        
        $databaseUsers = $databaseUser_model->findAllNotActive();
        $db_users = array();
        foreach($databaseUsers as $user)
        {
            $database = $database_model->FindByPK($user->getBaseId());
            $orderShared = $orderShared_model->findByOrderId($database->getOrderId());
            $db_users[$orderShared->getUnixLogin()] = array();
            $db_users[$orderShared->getUnixLogin()]['error'] = array();
            $db_users[$orderShared->getUnixLogin()]['error']['reason'] = array();
            $db_users[$orderShared->getUnixLogin()]['error']['object'] = array();
            $db_users[$orderShared->getUnixLogin()]['error']['action'] = array();
            $db_users[$orderShared->getUnixLogin()]['ok'] = array();
        }
        foreach($databaseUsers as $user)
        {
            $orderShared = $orderShared_model->findByOrderId($database->getOrderId());
            $result = $jabber->checkMessage($user->getMessageId());
            $result_explode = explode("::", $result);
            $result = $result_explode['0'];
            $action = $result_explode['1'];
            switch($result)
            {
                case "ok":
                    $message_model = new MessagesModel($em);
                    $message = new messages();
                    $action = str_replace("\"", "", $action);
                    $pars = explode(" ", $action);
                    
                    array_push($db_users[$orderShared->getUnixLogin()]['ok'], $user);
                    if ($user->getForRemove())
                    {
                        $databaseUser_model->removeByPK($user->getId());
                        $message->setMessage('Вы удалили mysql пользователя
                                  База: '.$pars['3'].'
                                  Пользователь: '.$pars['2']);
                        $message->setTheme('удаление mysql пользователя '.$pars['2']);
                    }
                    else
                    {
                        if (strstr($action, 'change'))
                        {
                            if (strstr($action, 'mysql_user_password'))
                            {
                                $message->setMessage('Вы изменили mysql пользователя
                                  База: '.$pars['3'].'
                                  Пользователь: '.$pars['2'].'
                                  Новый пароль: '.base64_decode($pars['4']));
                            }
                            else
                            {
                                $message->setMessage('Вы изменили mysql пользователя
                                  База: '.$pars['3'].'
                                  Пользователь: '.$pars['2'].'
                                  Новые права: '.$pars['4']);
                            }    
                            $message->setTheme('изменение mysql пользователя '.$pars['2']);
                        }
                        else
                        {
                            $message->setMessage('Вы создали mysql пользователя
                                          База: '.$pars['3'].'
                                          Пользователь: '.$pars['2'].'
                                          Пароль: '.base64_decode($pars['4']));
                            $message->setTheme('создание mysql пользователя '.$pars['2']);
                        }
                        $user->setIsActive("1");
                        $databaseUser_model->create($user);
                    }
                    
                    $message->setUserFrom('1');
                    $securityContext = $this->container->get('security.context');
                    $userCurrent = $securityContext->getToken()->getUser();
                    if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                        $message->setUserTo($this->get('session')->get('user')->getId());
                    else
                        $message->setUserTo($userCurrent->getId());
                    $message->setWasRead('0');
                    $message_model->create($message);
                    
                break;
                case "no":
                    continue;
                break;
                default:
                    array_push($db_users[$orderShared->getUnixLogin()]['error']['reason'], $result);
                    array_push($db_users[$orderShared->getUnixLogin()]['error']['object'], $user);
                    array_push($db_users[$orderShared->getUnixLogin()]['error']['action'], $action);
                    if ($user->getForRemove() || (strstr($action, 'change')))
                    {
                        $user->setIsActive("1");
                        $databaseUser_model->create($user);
                    }
                    else
                    {
                        $databaseUser_model->removeByPK($user->getId());
                    }
                break;
            }
        }
        $databases = $database_model->findAll();
        $db_string = array();
        foreach($databases as $database)
        {
            $db_string[$database->getId()] = $database->getName();
        }
        
        $databases = $database_model->findAllNotActive();
        $dbs = array();
        foreach($databases as $database)
        {
            $db_string[$database->getId()] = $database->getName();
            $orderShared = $orderShared_model->findByOrderId($database->getOrderId());
            $dbs[$orderShared->getUnixLogin()] = array();
            $dbs[$orderShared->getUnixLogin()]['error'] = array();
            $dbs[$orderShared->getUnixLogin()]['error']['reason'] = array();
            $dbs[$orderShared->getUnixLogin()]['error']['object'] = array();
            $dbs[$orderShared->getUnixLogin()]['error']['action'] = array();
            $dbs[$orderShared->getUnixLogin()]['ok'] = array();
        }
        foreach($databases as $database)
        {
            $orderShared = $orderShared_model->findByOrderId($database->getOrderId());
            $result = $jabber->checkMessage($database->getMessageId());
            $result_explode = explode("::", $result);
            //print_r($result_explode);
            $result = $result_explode['0'];
            $action = $result_explode['1'];
            switch($result)
            {
                case "ok":
                    $message_model = new MessagesModel($em);
                    $message = new messages();
                    $action = str_replace("\"", "", $action);
                    $pars = explode(" ", $action);
                    
                    array_push($dbs[$orderShared->getUnixLogin()]['ok'], $database);
                    if ($database->getForRemove())
                    {
                        $database_model->removeByPK($database->getId());
                        $message->setMessage('Вы удалили базу данных 
                                  База: '.$pars['2']);
                        $message->setTheme('удаление БД '.$pars['2']);
                    }
                    else
                    {
                        $database->setIsActive("1");
                        $database_model->create($database);
                        $message->setMessage('Вы создали базу данных 
                                  База: '.$pars['2'].'
                                  ip сервера: 127.0.0.1');
                        $message->setTheme('создание БД '.$pars['2']);
                    }
                    
                    $message->setUserFrom('1');
                    $securityContext = $this->container->get('security.context');
                    $userCurrent = $securityContext->getToken()->getUser();
                    if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                        $message->setUserTo($this->get('session')->get('user')->getId());
                    else
                        $message->setUserTo($userCurrent->getId());
                    $message->setWasRead('0');
                    $message_model->create($message);
            
                break;
                case "no":
                    continue;
                break;
                default:
                    array_push($dbs[$orderShared->getUnixLogin()]['error']['reason'], $result);
                    array_push($dbs[$orderShared->getUnixLogin()]['error']['object'], $database);
                    array_push($dbs[$orderShared->getUnixLogin()]['error']['action'], $action);
                    if ($database->getForRemove())
                    {
                        $database->setIsActive("1");
                        $database_model->create($database);
                    }
                    else
                    {
                        $database_model->removeByPK($database->getId());
                    }
                break;
            } 
        }

        $emails = $email_model->findAllNotActive();
        $ems = array();
        foreach($emails as $email)
        {
            $orderShared = $orderShared_model->findByOrderId($email->getOrderId());
            $ems[$orderShared->getUnixLogin()] = array();
            $ems[$orderShared->getUnixLogin()]['error'] = array();
            $ems[$orderShared->getUnixLogin()]['error']['reason'] = array();
            $ems[$orderShared->getUnixLogin()]['error']['object'] = array();
            $ems[$orderShared->getUnixLogin()]['error']['action'] = array();
            $ems[$orderShared->getUnixLogin()]['ok'] = array();
        }
        foreach($emails as $email)
        {
            $orderShared = $orderShared_model->findByOrderId($email->getOrderId());
            $result = $jabber->checkMessage($email->getMessageId());
            $result_explode = explode("::", $result);
            //print_r($result_explode);
            $result = $result_explode['0'];
            $action = $result_explode['1'];
            switch($result)
            {
                case "ok":
                    $message_model = new MessagesModel($em);
                    $message = new messages();
                    $action = str_replace("\"", "", $action);
                    $pars = explode(" ", $action);
                    
                    array_push($ems[$orderShared->getUnixLogin()]['ok'], $email);
                    if ($email->getForRemove())
                    {
                        $email_model->removeByPK($email->getId());
                        $message->setMessage('Вы удалили ящик '.$pars['3']);
                        $message->setTheme('удаление ящика '.$pars['3']);
                    }
                    else if (strstr($action, 'change'))
                    {
                        $email->setIsActive("1");
                        $email_model->create($email);
                        $message->setMessage('Вы изменили пароль для '.$pars['3'].'. Новый пароль: '.base64_decode($pars['4']));
                        $message->setTheme('изменение ящика '.$pars['3']);
                    }
                    else
                    {
                        $email->setIsActive("1");
                        $email_model->create($email);
                        $temp = explode("@", $pars['3']);
                        $message->setMessage('Вы добавили ящик
                                  Имя пользователя: '.$pars['3'].'
                                  Пароль: '.base64_decode($pars['4']).'
                                  Почтовый IMAP/POP3 сервер: mail.'.$temp['1'].'
                                  Почтовый SMTP сервер: mail.'.$temp['1']);
                        $message->setTheme('создание ящика '.$pars['3']);
                    }
                    
                    $message->setUserFrom('1');
                    $securityContext = $this->container->get('security.context');
                    $userCurrent = $securityContext->getToken()->getUser();
                    if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                        $message->setUserTo($this->get('session')->get('user')->getId());
                    else
                        $message->setUserTo($userCurrent->getId());
                    $message->setWasRead('0');
                    $message_model->create($message);
                    
                break;
                case "no":
                    continue;
                break;
                default:
                    array_push($ems[$orderShared->getUnixLogin()]['error']['reason'], $result);
                    array_push($ems[$orderShared->getUnixLogin()]['error']['object'], $email);
                    array_push($ems[$orderShared->getUnixLogin()]['error']['action'], $action);
                    if (($email->getForRemove()) || (strstr($action, 'change')))
                    {
                        $email->setIsActive("1");
                        $email_model->create($email);
                    }
                    else
                    {
                        $email_model->removeByPK($email->getId());
                    }
                break;
            }
        }
        
        $ftps = $ftp_model->findAllNotActive();
        $ft = array();
        foreach($ftps as $ftp)
        {
            $orderShared = $orderShared_model->findByOrderId($ftp->getOrderId());
            $ft[$orderShared->getUnixLogin()] = array();
            $ft[$orderShared->getUnixLogin()]['error'] = array();
            $ft[$orderShared->getUnixLogin()]['error']['reason'] = array();
            $ft[$orderShared->getUnixLogin()]['error']['object'] = array();
            $ft[$orderShared->getUnixLogin()]['error']['action'] = array();
            $ft[$orderShared->getUnixLogin()]['ok'] = array();
        }
        foreach($ftps as $ftp)
        {
            $orderShared = $orderShared_model->findByOrderId($ftp->getOrderId());
            $result = $jabber->checkMessage($ftp->getMessageId());
            $result_explode = explode("::", $result);
            //print_r($result_explode);
            $result = $result_explode['0'];
            $action = $result_explode['1'];
            switch($result)
            {
                case "ok":
                    $message_model = new MessagesModel($em);
                    $message = new messages();
                    $action = str_replace("\"", "", $action);
                    $pars = explode(" ", $action);
                    
                    array_push($ft[$orderShared->getUnixLogin()]['ok'], $ftp);
                    if ($ftp->getForRemove())
                    {
                        $ftp_model->removeByPK($ftp->getId());
                        $message->setMessage('Вы удалили ftp пользователя '.$pars['2']);
                        $message->setTheme('удаление ftp пользователя '.$pars['2']);
                    }
                    else if (strstr($action, 'change'))
                    {
                        $ftp->setIsActive("1");
                        $ftp_model->create($ftp);
                        $message->setMessage('Вы изменили пароль для '.$pars['2'].'. Новый пароль: '.base64_decode($pars['3']));
                        $message->setTheme('изменение ftp пользователя '.$pars['2']);
                    }
                    else
                    {
                        $ftp->setIsActive("1");
                        $ftp_model->create($ftp);
                        $message->setMessage('Вы добавили ftp пользователя
                                  Имя пользователя: '.$pars['2'].'
                                  Пароль: '.base64_decode($pars['3']).'
                                  Директория: '.$pars['4']);
                        $message->setTheme('создание ftp пользователя '.$pars['2']);
                    }
                    
                    $message->setUserFrom('1');
                    $securityContext = $this->container->get('security.context');
                    $userCurrent = $securityContext->getToken()->getUser();
                    if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                        $message->setUserTo($this->get('session')->get('user')->getId());
                    else
                        $message->setUserTo($userCurrent->getId());
                    $message->setWasRead('0');
                    $message_model->create($message);
                    
                break;
                case "no":
                    continue;
                break;
                default:
                    array_push($ft[$orderShared->getUnixLogin()]['error']['reason'], $result);
                    array_push($ft[$orderShared->getUnixLogin()]['error']['object'], $ftp);
                    array_push($ft[$orderShared->getUnixLogin()]['error']['action'], $action);
                    if (($ftp->getForRemove()) || (strstr($action, 'change')))
                    {
                        $ftp->setIsActive("1");
                        $ftp_model->create($ftp);
                    }
                    else
                    {
                        $ftp_model->removeByPK($ftp->getId());
                    }

                break;
            }
        }
        
        $dnss = $dns_model->findAllNotActive();
        $dn = array();
        foreach($dnss as $dns)
        {
            $domain = $domain_model->findByPK($dns->getDomainId());
            $orderShared = $orderShared_model->findByOrderId($domain->getOrderId());
            if (!isset($orderShared))
                continue;
            $dn[$orderShared->getUnixLogin()] = array();
            $dn[$orderShared->getUnixLogin()]['error'] = array();
            $dn[$orderShared->getUnixLogin()]['error']['reason'] = array();
            $dn[$orderShared->getUnixLogin()]['error']['object'] = array();
            $dn[$orderShared->getUnixLogin()]['error']['action'] = array();
            $dn[$orderShared->getUnixLogin()]['ok']['object'] = array();
            $dn[$orderShared->getUnixLogin()]['ok']['action'] = array();
        }
        foreach($dnss as $dns)
        {
            $domain = $domain_model->findByPK($dns->getDomainId());
            $orderShared = $orderShared_model->findByOrderId($domain->getOrderId());
            $result = $jabber->checkMessage($dns->getMessageId());
            $result_explode = explode("::", $result);
            //print_r($result_explode);
            $result = $result_explode['0'];
            $action = $result_explode['1'];
            switch($result)
            {
                case "ok":
                    $action = str_replace("\"", "", $action);
                    $pars = explode(" ", $action);
                    array_push($dn[$orderShared->getUnixLogin()]['ok']['object'], $dns);
                    array_push($dn[$orderShared->getUnixLogin()]['ok']['action'], $action);
                    if ($dns->getForRemove())
                    {
                        $dns_model->removeByPK($dns->getId());
                    }
                    else if (strstr($action, 'change'))
                    {
                        $new_name = $pars['6'];
                        $new_type = $pars['7'];
                        $new_value = $pars['8'];
                        $dns->setName($new_name);
                        $dns->setType($new_type);
                        $dns->setValue($new_value);
                        $dns->setIsActive("1");
                        $dns_model->create($dns);
                    }
                    else
                    {
                        $dns->setIsActive("1");
                        $dns_model->create($dns);
                    }                    
                break;
                case "no":
                    continue;
                break;
                default:
                    array_push($dn[$orderShared->getUnixLogin()]['error']['reason'], $result);
                    array_push($dn[$orderShared->getUnixLogin()]['error']['object'], $dns);
                    array_push($dn[$orderShared->getUnixLogin()]['error']['action'], $action);
                    if (($dns->getForRemove()) || (strstr($action, 'change')))
                    {
                        $dns->setIsActive("1");
                        $dns_model->create($dns);
                    }
                    else
                    {
                        $dns_model->removeByPK($dns->getId());
                    }

                break;
            }
        }
        
        $domains = $domain_model->findAllNotActive();
        $ds = array();
        foreach($domains as $domain)
        {
            $result = $jabber->checkMessage($domain->getMessageId());
            $result_explode = explode("::", $result);
            $result = $result_explode['0'];
            $action = $result_explode['1'];
            if (!$action)
                continue;
            $action = str_replace("\"", "", $action);
            $pars = explode(" ", $action);
            $temp = explode("|", $pars['2']);
            $unix_login = $temp['0'];
            $ds[$unix_login] = array();
            $ds[$unix_login]['error'] = array();
            $ds[$unix_login]['error']['reason'] = array();
            $ds[$unix_login]['error']['object'] = array();
            $ds[$unix_login]['error']['action'] = array();
            $ds[$unix_login]['ok']['object'] = array();
            $ds[$unix_login]['ok']['action'] = array();
            
            switch($result)
            {
                case "ok":
                    $action = str_replace("\"", "", $action);
                    $pars = explode(" ", $action);
                    array_push($ds[$unix_login]['ok']['object'], $domain);
                    array_push($ds[$unix_login]['ok']['action'], $action);
                    $dnss = $dns_model->findByDomainId($domain->getId());
                    if ($domain->getForRemove())
                    {
                        foreach($dnss as $dns)
                        {
                            $dns_model->removeByPK($dns->getId());
                        }
                        $domain_model->removeByPK($domain->getId());
                    }
                    else
                    {
                        foreach($dnss as $dns)
                        {
                            $dns->setIsActive("1");
                            $dns_model->create($dns);
                        }
                        $domain->setIsActive("1");
                        $domain_model->create($domain);
                    }                    
                break;
                case "no":
                    continue;
                break;
                default:
                    array_push($ds[$unix_login]['error']['reason'], $result);
                    array_push($ds[$unix_login]['error']['object'], $domain);
                    array_push($ds[$unix_login]['error']['action'], $action);
                    if ($domain->getForRemove())
                    {
                        $domain->setIsActive("1");
                        $domain_model->create($domain);
                    }
                    else
                    {
                        $domain_model->removeByPK($domain->getId());
                    }

                break;
            }
        }
        //print_r($ems);
        $domains = $domain_model->findAll();
        $domain_string = array();
        foreach($domains as $domain)
        {
            $domain_string[$domain->getId()] = $domain->getName();
        }
        return $this->render('BillingBundle:Orders_shared:user_index_js.html.twig', array('db_users' =>$db_users, 'databases'=>$dbs, 'emails'=>$ems, 'ftps'=>$ft, 'dnss'=>$dn, 'db_string'=>$db_string, 'domain_string'=>$domain_string));
    }
    public function dnsActiveAction()
    {
        $order_name = $_POST['order'];
        $hash = $_POST['hash'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        //$domain_model = new DomainsModel($em);
        $domainDns_model = new DomainsDnsModel($em);
        //$domain = $domain_model->findByDomainName($domain_name);
        $domainDns = $domainDns_model->findByHash($hash);
        $dns_hashs[$domainDns->getId()] = $hash;
        return $this->render('BillingBundle:Orders_shared:user_index_active_dns_template.html.twig', array('order_name' => $order_name, 'domainDns' => $domainDns, 'dns_hashs' => $dns_hashs));   
    }
    public function dnsNotActiveAction()
    {
        $order_name = $_POST['order'];
        $hash = $_POST['hash'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        //$domain_model = new DomainsModel($em);
        $domainDns_model = new DomainsDnsModel($em);
        //$domain = $domain_model->findByDomainName($domain_name);
        $domainDns = $domainDns_model->findByHash($hash);
        $dns_hashs[$domainDns->getId()] = $hash;
        return $this->render('BillingBundle:Orders_shared:user_index_not_active_dns_template.html.twig', array('order_name' => $order_name, 'domainDns' => $domainDns, 'dns_hashs' => $dns_hashs));   
    }
    public function databaseActiveAction()
    {
        $order_name = $_POST['order'];
        $base_name = $_POST['base'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        $database_model = new OrdersSharedMysqlModel($em);
        $database = $database_model->FindByBaseNameAndOrderId($base_name, $orderShared->getOrderId());
        $databaseUser_model = new OrdersSharedMysqlUsersModel($em);

        $base = array();
        $base['database'] = $database;
        $base['users'] = array();
        $rights = array();
        $users = $databaseUser_model->findByBaseId($database->getId());
        foreach($users as $user)
        {
            array_push($base['users'], $user);
            $rights[$user->getId()] = $user->getUserRightsArray();
        }
        return $this->render('BillingBundle:Orders_shared:user_index_active_database_template.html.twig', array('base' => $base, 'order_name' => $orderShared->getUnixLogin(), 'rights' => $rights));   
    }
    public function databaseNotActiveAction()
    {
        $order_name = $_POST['order'];
        $base_name = $_POST['base'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        $database_model = new OrdersSharedMysqlModel($em);
        $database = $database_model->FindByBaseNameAndOrderId($base_name, $orderShared->getOrderId());
        $databaseUser_model = new OrdersSharedMysqlUsersModel($em);
        
        $base = array();
        $base['database'] = $database;
        $base['users'] = array();
        $rights = array();
        $users = $databaseUser_model->findByBaseId($database->getId());
        foreach($users as $user)
        {
            array_push($base['users'], $user);
            $rights[$user->getId()] = $user->getUserRightsArray();
        }
        return $this->render('BillingBundle:Orders_shared:user_index_not_active_database_template.html.twig', array('base' => $base, 'order_name' => $orderShared->getUnixLogin(), 'rights' => $rights));   
    }
    public function dbuserActiveAction()
    {
        $order_name = $_POST['order'];
        $base_name = $_POST['base'];
        $user_name = $_POST['user'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        $database_model = new OrdersSharedMysqlModel($em);
        $database = $database_model->FindByBaseNameAndOrderId($base_name, $orderShared->getOrderId());
        $databaseUser_model = new OrdersSharedMysqlUsersModel($em);
        
        $base = array();
        $base['database'] = $database;
        $user = $databaseUser_model->findByBaseIdAndLogin($database->getId(), $user_name);
        $rights[$user->getId()] = $user->getUserRightsArray();
        return $this->render('BillingBundle:Orders_shared:user_index_active_dbuser_template.html.twig', array('base'=>$base, 'user' => $user, 'order_name' => $orderShared->getUnixLogin(), 'rights' => $rights));   
    }
    public function dbuserNotActiveAction()
    {
        $order_name = $_POST['order'];
        $base_name = $_POST['base'];
        $user_name = $_POST['user'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        $database_model = new OrdersSharedMysqlModel($em);
        $database = $database_model->FindByBaseNameAndOrderId($base_name, $orderShared->getOrderId());
        $databaseUser_model = new OrdersSharedMysqlUsersModel($em);
        
        $base = array();
        $base['database'] = $database;
        $user = $databaseUser_model->findByBaseIdAndLogin($database->getId(), $user_name);
        $rights[$user->getId()] = $user->getUserRightsArray();
        return $this->render('BillingBundle:Orders_shared:user_index_not_active_dbuser_template.html.twig', array('base'=>$base, 'user' => $user, 'order_name' => $orderShared->getUnixLogin(), 'rights' => $rights));   
    }
    public function emailActiveAction()
    {
        $order_name = $_POST['order'];
        $email_name = $_POST['email'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        $email_model = new OrdersSharedEmailModel($em);
        $result = explode("@", $email_name);
        $email = $email_model->findByUserAndDomainAndOrderId($result['0'], $result['1'], $orderShared->getOrderId());

        $domain_array = array();
        $domain_array['domain'] = $result['1'];

        return $this->render('BillingBundle:Orders_shared:user_index_active_email_template.html.twig', array('domain' => $domain_array, 'order_name' => $orderShared->getUnixLogin(), 'email'=>$email));   
    }
    public function emailNotActiveAction()
    {
        $order_name = $_POST['order'];
        $email_name = $_POST['email'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        $email_model = new OrdersSharedEmailModel($em);
        $result = explode("@", $email_name);
        $email = $email_model->findByUserAndDomainAndOrderId($result['0'], $result['1'], $orderShared->getOrderId());
        
        $domain_array = array();
        $domain_array['domain'] = $result['1'];

        return $this->render('BillingBundle:Orders_shared:user_index_not_active_email_template.html.twig', array('domain' => $domain_array, 'order_name' => $orderShared->getUnixLogin(), 'email'=>$email));   
    }
    public function ftpActiveAction()
    {
        $order_name = $_POST['order'];
        $user = $_POST['user'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        
        $ftp_model = new OrdersSharedFtpModel($em);
        $ftp = $ftp_model->findByUserAndOrderId($user, $orderShared->getOrderId());
        
        if (!isset($ftp))
            return new Response('');
        return $this->render('BillingBundle:Orders_shared:user_index_active_ftp_template.html.twig', array('order_name' => $orderShared->getUnixLogin(), 'ftp' => $ftp));   
    }
    public function ftpNotActiveAction()
    {
        $order_name = $_POST['order'];
        $user = $_POST['user'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $orderShared = $orderShared_model->findByOrderName($order_name);
        
        $ftp_model = new OrdersSharedFtpModel($em);
        $ftp = $ftp_model->findByUserAndOrderId($user, $orderShared->getOrderId());
        
        if (!isset($ftp))
            return new Response('');
        return $this->render('BillingBundle:Orders_shared:user_index_not_active_ftp_template.html.twig', array('order_name' => $orderShared->getUnixLogin(), 'ftp' => $ftp));   
    }
    public function addAction()
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        $orderShared_model = new OrdersSharedModel($em);
        $user_model = new UsersModel($em);
        $totalTransaction_model = new UsersTotalTransactionsModel($em);
        $transaction_model = new UsersTransactionsModel($em);
        $bonus_model = new BonusesModel($em);
        $bonusTable_model = new BonusesTableModel($em);
        $zone_model = new DomainsZonesModel($em);
        $domain_model = new DomainsModel($em);
        $bill_model = new UsersBillsModel($em);
        
        $dir=opendir(dirName('../'.basename(__FILE__)).'/vendor/mpanel/classes/Bonuses/');
        $file_string = array();
        while ($file = readdir($dir))
        {
            if (in_array($file,array('.','..')))
                continue;
            $expl=explode('.', $file);
            $expl_size=sizeof($expl);
            if (mb_strtolower($expl[$expl_size-1],'UTF-8') != 'php')
                continue;
            $file_len = sizeof($file_string);
            $file_string[$file_len] = $file;
        }
        closedir($dir);
        array_multisort($file_string);
        $names = array();
        $coupons = array();
        foreach($file_string as $coupon)
        {
            $expl=explode('.', $coupon);
            $class_name = $expl['0'];
            $class_name = 'Bonuses_'.$class_name;
            $check_domain = $this->get('check_domain');
            $class = $class_name::newInstance(NULL, NULL, NULL, $check_domain, $em);
            array_push($names, $class_name);
            array_push($coupons, $class->getTitle());
        }
        
        $coupons_string = array();
        if ($userCurrent == 'anon.')
            $bonusesTable = array();
        else
            $bonusesTable = $bonusTable_model->findByUserIdAndActive($userCurrent->getId(), '1');
        foreach($bonusesTable as $bonusTable)
        {
            $bonus = $bonus_model->findByPK($bonusTable->getBonusId());
            if ($bonus->getCoupon() != 'no')
            {
                foreach($names as $key => $name)
                {
                    if ($name == $bonus->getCoupon())
                        array_push($coupons_string, $coupons[$key]);
                }
            }
        }
        
        $password = new GeneratePassword();
        $registered = true;
        if ($userCurrent == 'anon.')
        {
            $registered = false;
            $securityEncoderFactory = $this->get('security.encoder_factory');
            $userCurrent = new users($securityEncoderFactory);
            $userCurrent->setStatusId('2');
            $userCurrent->setPassword($password->generatePassword(8, 2));
        }
        $orderShared = new ordersShared();
        //$orderShared_model->create($orderShared->initDefaultEntity());//создание по умолчанию
        //return new RedirectResponse($this->generateUrl('orders_shared_show'));
        $zones = $zone_model->findByAllActive();
        $zone_string = array();
        foreach($zones as $zone)
        {
            if ($zone->getName() == "xn--p1ai")
                $name = "рф";
            else
                $name = $zone->getName();
            $zone_string[$name] = $zone;
        }
        $tarif_model = new OrdersSharedTarifModel($em);
        //$tarifTerms_model = new OrdersTarifsTermsModel($em);
        $tarifs = $tarif_model->findAll();  
        $tarif_string = array();
        //$tarifTerms_string = array();
        foreach($tarifs as $tarif)
        {
            if (($userCurrent->isAdmin() && !$this->get('session')->get('user')) || $tarif->getIsActive())
            {
                $tarif_string[$tarif->getId()] = ' ';
                        
                /*$tarifsTerms = $tarifTerms_model->findByTarif($tarif->getId(), 1);
                $tarifTerm_string[$tarif->getId()] = array();
                foreach($tarifsTerms as $tarifsTerm)
                {
                    $tarifTerms_string[$tarif->getId()][$tarifsTerm->getId()] = $tarifsTerm;
                }   */
            }
        }

        /*
        
        $bonus_model = new BonusesModel($em);
        $bonuses = $bonus_model->findAll();
        $bonuses_string = array();
        $coupons_string = array();
        $bonuses_with_id = array();*/

        $errors = array();
        /*foreach($tarifs as $tarif)
        {
            $bonuses_string[$tarif->getId()] = array();
            $coupons_string[$tarif->getId()] = array();
            $bonuses_with_id[$tarif->getId()] = array();
            if (($userCurrent->isAdmin() && !$this->get('session')->get('user')) || $tarif->getIsActive())
            {
                $tarifsTerms = $tarifTerms_model->findByTarif($tarif->getId(), 1);
                if (!isset($tarifsTerms['0']))
                    array_push($errors, array('message' => 'Сроки созданы не для всех тарифов!', 'link' => 'terms_add'));
                foreach($tarifsTerms as $tarifsTerm)
                {
                    $cost = $tarif->getCost() * $tarifsTerm->getTerm() * 30;

                    $bonuses_string[$tarif->getId()][$tarifsTerm->getTerm()] = array();
                    $coupons_string[$tarif->getId()][$tarifsTerm->getTerm()] = array();
                    $bonuses_with_id[$tarif->getId()][$tarifsTerm->getTerm()] = array();
                    foreach($bonuses as $bonus)
                    {
                        if (($bonus->getIsActive()) && ($bonus->getSum() <= $cost))
                        {
                            array_push($bonuses_string[$tarif->getId()][$tarifsTerm->getTerm()], '+бонус '.$bonus->getPercent().'% - '.($cost * 30 * $bonus->getPercent() / 100).' руб. на счет в подарок');
                            array_push($bonuses_with_id[$tarif->getId()][$tarifsTerm->getTerm()], $bonus->getId());
                            if ($bonus->getCoupon() != 'no')
                            {
                                foreach($names as $key => $name)
                                {
                                    if ($name == $bonus->getCoupon())
                                        array_push($coupons_string[$tarif->getId()][$tarifsTerm->getTerm()], '+'.$coupons[$key]);
                                }
                            }
                        }
                    }
                }
            }
        }*/

        if (count($tarif_string) == 0)
            array_push($errors, array('message' => 'Тарифы не созданы!', 'link' => 'sharedTarifs_add'));
        //if (count($tarifTerms_string) == 0)
        //    array_push($errors, array('message' => 'Сроки не созданы!', 'link' => 'terms_add'));
        $errors = array_unique($errors);
        if (count($errors) != 0)
        {
            if ($userCurrent->isAdmin())
            {
                if ($this->get('session')->get('user'))
                    return $this->render('BillingBundle:Orders_shared:user_error.html.twig', array('errors' => $errors));
                else
                    return $this->render('BillingBundle:Orders_shared:admin_error.html.twig', array('errors' => $errors));
            }
            else
                return $this->render('BillingBundle:Orders_shared:user_error.html.twig', array('errors' => $errors));
        }
        $form = $this->createForm(new OrdersSharedForm($tarif_string), $orderShared);

        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if ($form->isValid())
            {
                if (!$registered)
                {
                    if ($user_model->checkByLogin($_POST['email']))
                    {
                        $userCurrent = $user_model->findByLogin($_POST['email']);
                        
                        $template_model = new TemplatesModel($em);
                        $tpl_engine = $this->get('twigstring');
                        $template_layout = $template_model->findByName('layout');
                        $template = $template_model->findByName('autologin');
                        
                        $content = $tpl_engine->render($template->getBody(), array('user' => $userCurrent));
                        $body = $template_layout->getBody();
                        $mailer = $this->get('mailer');
                        $body = str_replace('{{ content }}', $content, $body);

                        $message = \Swift_Message::newInstance()
                            ->setSubject($template->getTheme())
                            ->setFrom('do.not.reply@docker.ru')
                            ->setTo($userCurrent->getLogin())
                            ->setBody($body, 'text/html');
                        $mailer->send($message);
                    }
                    else
                    {
                        $userCurrent->setLogin($_POST['email']);
                        $user_model->create($userCurrent);

                        $acl = $this->get('acl');
                        $acl->createPermissionsForOne($userCurrent, $userCurrent, MaskBuilder::MASK_OWNER);
                        $acl->createPermissionsForAllAdmins($userCurrent);

                        $totalTransaction = new usersTotalTransactions();
                        $totalTransaction->setMoney('0');
                        $totalTransaction->setUserId($userCurrent->getId());
                        $totalTransaction_model->create($totalTransaction);

                        $template_model = new TemplatesModel($em);
                        $tpl_engine = $this->get('twigstring');
                        $template_layout = $template_model->findByName('layout');
                        $template = $template_model->findByName('new_order_user');
                        
                        $content = $tpl_engine->render($template->getBody(), array('user' => $userCurrent));
                        $body = $template_layout->getBody();//$tpl_engine->render($template_layout->getBody(), array('content' => $content));
                        $mailer = $this->get('mailer');
                        $body = str_replace('{{ content }}', $content, $body);
                        /*$message = \Swift_Message::newInstance()
                            ->setSubject('Создание заказа на виртульный хостинг')
                            ->setFrom('do.not.reply@docker.ru')
                            ->setTo($userCurrent->getLogin())
                            ->setBody($this->renderView('BillingBundle:Orders_shared:password_mail.html.twig', array('user' => $userCurrent)), 'text/html');
                        $mailer->send($message);*/
                        $message = \Swift_Message::newInstance()
                            ->setSubject($template->getTheme())
                            ->setFrom('do.not.reply@docker.ru')
                            ->setTo($userCurrent->getLogin())
                            ->setBody($body, 'text/html');
                        $mailer->send($message);
                        
                        $securityContext = $this->container->get('security.context');
                        $token = new UsernamePasswordToken($userCurrent, null, 'users_provider', $userCurrent->getRoles());
                        $securityContext->setToken($token);
                    }
                }

                $order = new orders();
                $order->setIsActive('0');
                $order->setType('1');//виртуальный хостинг
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $order->setUserId($this->get('session')->get('user')->getId());
                else
                    $order->setUserId($userCurrent->getId());
                $order_model = new OrdersModel($em);
                $order_model->create($order);

                $acl = $this->get('acl');
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $acl->createPermissionsForOne($order, $this->get('session')->get('user'), MaskBuilder::MASK_OWNER);
                else
                    $acl->createPermissionsForOne($order, $userCurrent, MaskBuilder::MASK_OWNER);
                $acl->createPermissionsForAllAdmins($order);

                $tarif_id = $form['shared_tarif']->getData();
                $tarif = $tarif_model->findByPK($tarif_id);

                $domain_selected = $_POST['hide_domain'];
                switch ($domain_selected)
                {
                    case 1:
                        $check_domain = $this->get('check_domain');
                        $check_domain->init($orderShared->getDomain());
                        $zone = $zone_model->findByName($check_domain->get_tld());

                        $domain = new domains();
                        $domain->setName($orderShared->getDomain());
                        $domain->setOrderId($order->getId());
                        $domain->setZoneId($zone->getId());
                        $domain->setStatusId('1');
                        $domain->setIsActive('0');
                        $domain->setForRemove('0');
                        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                            $domain->setUserId ($this->get('session')->get('user')->getId());
                        else
                            $domain->setUserId ($userCurrent->getId());
                        $domain_model->create($domain);
                        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                            $acl->createPermissionsForOne($domain, $this->get('session')->get('user'), MaskBuilder::MASK_OWNER);
                        else
                            $acl->createPermissionsForOne($domain, $userCurrent, MaskBuilder::MASK_OWNER);
                        $acl->createPermissionsForAllAdmins($domain);
                        
                        $orderShared->setStatus('3');
                    break;
                    case 2:
                        $domain = new domains();
                        $domain = $domain->initGuestEntity();

                        $check_domain = $this->get('check_domain');
                        $check_domain->init($domain->getName());
                        $zone = $zone_model->findByName($check_domain->get_tld());
                        $domain->setZoneId($zone->getId());
                        $domain->setOrderId($order->getId());
                        $domain->setIsActive('0');
                        $domain->setForRemove('0');
                        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                            $domain->setUserId ($this->get('session')->get('user')->getId());
                        else
                            $domain->setUserId ($userCurrent->getId());
                        $domain_model->create($domain);
                        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                            $acl->createPermissionsForOne($domain, $this->get('session')->get('user'), MaskBuilder::MASK_OWNER);
                        else
                            $acl->createPermissionsForOne($domain, $userCurrent, MaskBuilder::MASK_OWNER);
                        $acl->createPermissionsForAllAdmins($domain);
                        
                        $orderShared->setStatus('4');
                        $orderShared->setDomain($domain->getName());
                    break;
                    case 3:
                        $check_domain = $this->get('check_domain');
                        $check_domain->init($orderShared->getDomain());
                        $zone = $zone_model->findByName($check_domain->get_tld());

                        $domain = new domains();
                        $domain->setName($orderShared->getDomain());
                        $domain->setOrderId($order->getId());
                        $domain->setZoneId($zone->getId());
                        $domain->setStatusId('1');
                        $domain->setIsActive('0');
                        $domain->setForRemove('0');
                        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                            $domain->setUserId ($this->get('session')->get('user')->getId());
                        else
                            $domain->setUserId ($userCurrent->getId());
                        $domain_model->create($domain);
                        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                            $acl->createPermissionsForOne($domain, $this->get('session')->get('user'), MaskBuilder::MASK_OWNER);
                        else
                            $acl->createPermissionsForOne($domain, $userCurrent, MaskBuilder::MASK_OWNER);
                        $acl->createPermissionsForAllAdmins($domain);
                        
                        $orderShared->setStatus('1');
                    break;
                    case 4:
                        $orderShared->setStatus('1');
                    break;
                    case 5:
                        $orderShared->setStatus('0');
                    break;
                }
                if ($orderShared->getStatus() == '5')
                {
                    $bill = new usersBills();
                    $bill->setMoney($zone->getRegCost());
                    $bill->setIsReal('1');
                    $bill->setIsPaid('0');
                    $bill->setSourceId('0');
                    if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                        $bill->setUserId($this->get('session')->get('user')->getId());
                    else
                        $bill->setUserId($userCurrent->getId());
                    $bill->setCurrencyId('1');
                    $bill->setOrderId($order->getId());
                    $bill->setDomainId($domain->getId());
                    $bill->setType('4');
                    $bill_model->create($bill);                    
                }
                
                $orderShared_model->create($form->getData(), $tarif, $order);
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $acl->createPermissionsForOne($orderShared, $this->get('session')->get('user'), MaskBuilder::MASK_OWNER);
                else
                    $acl->createPermissionsForOne($orderShared, $userCurrent, MaskBuilder::MASK_OWNER);
                $acl->createPermissionsForAllAdmins($orderShared);
                
                $bill = new usersBills();
                if ($orderShared->getStatus() == '3')
                    $reg_cost = $zone->getRegCost();
                else
                    $reg_cost = 0;

                //$period = $_POST['hide_period'];
                //$cost = $tarif->getCost()*$period*30;
                $cost = 0;
                $bill->setMoney($cost + $reg_cost);
                $bill->setIsReal('1');
                $bill->setSourceId('0');
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $bill->setUserId($this->get('session')->get('user')->getId());
                else
                    $bill->setUserId($userCurrent->getId());
                $bill->setCurrencyId('1');
                $bill->setOrderId($orderShared->getOrderId());
                if ($orderShared->getStatus() >= 3)
                    $bill->setDomainId($domain->getId());
                $bill->setType('1');
                //$bill->setPeriod($period);
                if ($tarif->getCost() == '0')
                    $bill->setIsPaid('1');
                else         
                    $bill->setIsPaid('0');
                $bill_model->create($bill);
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $acl->createPermissionsForOne($bill, $this->get('session')->get('user'), MaskBuilder::MASK_OWNER);
                else
                    $acl->createPermissionsForOne($bill, $userCurrent, MaskBuilder::MASK_OWNER);
                $acl->createPermissionsForAllAdmins($bill);

                /*$transaction = new usersTransactions();
                $transaction->setMoney($tarif->getCost());
                $transaction->setOrderId($bill->getOrderId());
                $transaction->setUserId($bill->getUserId());
                $transaction->setBillId($bill->getId());
                $transaction->setIsAdding('0');
                $transaction->setIsRegular('1');
                $transaction->setIsActive('1');
                $transaction_model->create($transaction);*/

                if ($domain_selected <= 2)
                {
                    $check_domain = $this->get('check_domain');
                    $zone_model = new DomainsZonesModel($em);
                    $zone = $zone_model->findByName($check_domain->get_tld());
                    $transaction = new usersTransactions();

                    if ($domain_selected == 2)
                    {
                        $check_domain->init($domain->getName());
                        $transaction->setMoney('0');
                    }
                    else
                    {
                        $check_domain->init($orderShared->getDomain());
                        $transaction->setMoney($zone->getRegCost());
                    }
                    
                    /*$transaction->setOrderId($bill->getOrderId());
                    $transaction->setUserId($bill->getUserId());
                    $transaction->setBillId($bill->getId());
                    $transaction->setIsAdding('0');
                    $transaction->setIsRegular('0');
                    $transaction->setIsActive('1');
                    $transaction_model->create($transaction);*/
                }

                /*if (count($bonuses_with_id[$tarif->getId()][$period]) > 0)
                {
                    foreach($bonuses_with_id[$tarif->getId()][$period] as $bonus)
                    {
                        $bonusTable = new bonusesTable();
                        $bonusTable->setBonusId($bonus);
                        $bonusTable->setIsActive('1');
                        $bonusTable->setUserId($bill->getUserId());
                        $bonusTable_model->create($bonusTable);
                    }
                }*/

                $log_model = new UsersLogsModel($em);
                $log = new usersLogs();
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $log->setUserId($this->get('session')->get('user')->getId());
                else
                    $log->setUserId($userCurrent->getId());
                $log->setActionTypeId('1');//создание заказа
                $log->setOrderId($orderShared->getOrderId());
                $log_model->create($log);
                
                return new Response(md5($bill->getId().$userCurrent->getSalt()));
                //return new RedirectResponse($this->generateUrl('panel'));
            }
        }
        $costById = array();
        foreach($tarifs as $tarif)
        {
            $costById[$tarif->getId()] = $tarif->getCost();
        }
        if ($userCurrent->isAdmin())
        {
            if ($this->get('session')->get('user'))
                //return $this->render('BillingBundle:Orders_shared:user_create.html.twig', array('form' => $form->createView(), 'tarifs' => $tarifs, 'costById' => $costById, 'tarifTerms' => $tarifTerms_string, 'bonuses' => $bonuses_string, 'coupons' => $coupons_string, 'registered' => $registered));
                return $this->render('BillingBundle:Orders_shared:user_create.html.twig', array('form' => $form->createView(), 'tarifs' => $tarifs, 'costById' => $costById, 'registered' => $registered, 'zones' => $zone_string, 'coupons' => $coupons_string));
            else
                return $this->render('BillingBundle:Orders_shared:admin_create.html.twig', array('form' => $form->createView(), 'tarifs' => $tarifs, 'costById' => $costById, 'registered' => $registered, 'zones' => $zone_string, 'coupons' => $coupons_string));
        }
        else
            return $this->render('BillingBundle:Orders_shared:user_create.html.twig', array('form' => $form->createView(), 'tarifs' => $tarifs, 'costById' => $costById, 'registered' => $registered, 'zones' => $zone_string, 'coupons' => $coupons_string));
    }
    public function updateAction()
    {
        $order_name = $_POST['order'];
        
        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);

        $orderShared = $orderShared_model->findByOrderName($order_name);
        $order_id = $orderShared->getOrderId();//чтобы сохранился order_id
        
        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        $acl = $this->get('acl');
        $acl->checkPermissions($orderShared, 'EDIT');

        $tarif_model = new OrdersSharedTarifModel($em);
        $tarifTerms_model = new OrdersTarifsTermsModel($em);
        $tarifs = $tarif_model->findAll();
        $temp_array = array();
        $tarifTerms_string = array();
        foreach($tarifs as $tarif)
        {
            if (($userCurrent->isAdmin() && !$this->get('session')->get('user')) || $tarif->getIsActive())
            {
                $tarif_string[$tarif->getId()] = $tarif->getName().' ('.$tarif->getHdd().'Мбайт) - '.$tarif->getCost().' в день';
                $tarifsTerms = $tarifTerms_model->findByTarif($tarif->getId(), 1);
                $tarifTerm_string[$tarif->getId()] = array();
                foreach($tarifsTerms as $tarifsTerm)
                {
                    $tarifTerms_string[$tarif->getId()][$tarifsTerm->getTerm()] = $tarifsTerm->getTerm();
                }
            }
        }
        $form = $this->createForm(new OrdersSharedForm($tarif_string), $orderShared);

        $request = $this->get('request');
        if ($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            if ($form->isValid())
            {
                $order_model = new OrdersModel($em);
                $order = $order_model->findByPK($order_id);
                $tarif = $tarif_model->findByPK($form['shared_tarif']->getData());
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $orderShared_model->update($form->getData(), $this->get('session')->get('user'), $tarif, $order);
                else
                    $orderShared_model->update($form->getData(), $userCurrent, $tarif, $order);
                return new RedirectResponse($this->generateUrl('orders_shared_show'));
            }
        }
        $costById = array();
        foreach($tarifs as $tarif)
        {
            $costById[$tarif->getId()] = $tarif->getCost();
        }
        
        //добавить обновление счетов и доменов
        if ($userCurrent->isAdmin())
        {
            if ($this->get('session')->get('user'))
                return $this->render('BillingBundle:Orders_shared:user_update.html.twig', array('form' => $form->createView(), 'tarifs' => $tarifs, 'costById' => $costById, 'tarifTerms' => $tarifTerms_string));
            else
                return $this->render('BillingBundle:Orders_shared:admin_update.html.twig', array('form' => $form->createView(), 'tarifs' => $tarifs, 'costById' => $costById, 'tarifTerms' => $tarifTerms_string));
        }
        else
            return $this->render('BillingBundle:Orders_shared:user_update.html.twig', array('form' => $form->createView(), 'tarifs' => $tarifs, 'costById' => $costById, 'tarifTerms' => $tarifTerms_string));
    }
    public function removeAction()
    {
        $order_name = $_POST['order'];

        $em = $this->get('doctrine.orm.entity_manager');
        $orderShared_model = new OrdersSharedModel($em);
        $order_model = new OrdersModel($em);
        $domain_model = new DomainsModel($em);
        
        $orderShared = $orderShared_model->findByOrderName($order_name);
        $order = $order_model->findByPK($orderShared->getOrderId());
        $domains = $domain_model->findByOrderId($orderShared->getOrderId());

        $securityContext = $this->container->get('security.context');
        $userCurrent = $securityContext->getToken()->getUser();
        $acl = $this->get('acl');
        $acl->checkPermissions($order, 'DELETE');
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $acl->removePermissionsForOne($order, $this->get('session')->get('user'));
        else
            $acl->removePermissionsForOne($order, $userCurrent);
        $acl->removePermissionsForAllAdmins($order);
        $acl->checkPermissions($orderShared, 'DELETE');
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $acl->removePermissionsForOne($orderShared, $this->get('session')->get('user'));
        else
            $acl->removePermissionsForOne($orderShared, $userCurrent);
        $acl->removePermissionsForAllAdmins($orderShared);
        if (isset($domains['0']))
        {
            foreach($domains as $domain)
            {
                $acl->checkPermissions($domain, 'DELETE');
                if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
                    $acl->removePermissionsForOne($domain, $this->get('session')->get('user'));
                else
                    $acl->removePermissionsForOne($domain, $userCurrent);
                $acl->removePermissionsForAllAdmins($domain);
                $domain_model->removeByPK($domain->getId());
            }
        }
        $order_model->removeByPK($orderShared->getOrderId());
                
        $bill_model = new UsersBillsModel($em);
        $bill = $bill_model->findByOrderId($orderShared->getOrderId());
        $acl->checkPermissions($bill, 'DELETE');
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $acl->removePermissionsForOne($bill, $this->get('session')->get('user'));
        else
            $acl->removePermissionsForOne($bill, $userCurrent);
        $acl->removePermissionsForAllAdmins($bill);
        
        $bill_model->removeByOrderId($orderShared->getOrderId());
        
        $orderShared_model->removeByPK($orderShared->getId());

        $log_model = new UsersLogsModel($em);
        $log = new usersLogs();
        if ($userCurrent->isAdmin() && $this->get('session')->get('user'))
            $log->setUserId($this->get('session')->get('user')->getId());
        else
            $log->setUserId($userCurrent->getId());
        $log->setActionTypeId('3');//удаление заказа
        $log->setOrderId($orderShared->getOrderId());
        $log_model->create($log);

        return new RedirectResponse($this->generateUrl('orders_shared_show'));
    }
    public function checkDomainAction($domain_name)
    {
        $check_domain = $this->get('check_domain');

        $check_domain->init($domain_name);
        if ($check_domain->is_valid())
        {
            if ($check_domain->is_available_zone())
            {
                if ($check_domain->is_not_regOnServer())
                {
                    if ($check_domain->is_not_stopDomain())
                    {
                        return new Response('true');
                    }
                    else
                    {
                        return new Response('Домен содержится в списке стоп-доменов');
                    }
                }
                else
                {
                    return new Response('Домен уже зарегистрирован на сервере');
                }
            }
            else
            {
                return new Response('Зона не доступна на сервере');  
            }
        }
        else
        {
            return new Response('Неправильный формат домена');
        }
    }
    public function checkNewDomainAction($domain_name)
    {
        $check_domain = $this->get('check_domain');

        $check_domain->init($domain_name);
        if ($check_domain->is_valid())
        {
            if ($check_domain->is_available_zone())
            {
                if ($check_domain->is_not_regOnServer())
                {
                    if ($check_domain->is_not_stopDomain())
                    {
                        if (!$check_domain->is_available())
                        {
                            return new Response('true');
                        }
                        else
                        {
                            return new Response('Домен уже занят');
                        }
                    }
                    else
                    {
                        return new Response('Домен содержится в списке стоп-доменов');
                    }
                }
                else
                {
                    return new Response('Домен уже зарегистрирован на сервере');
                }
            }
            else
            {
                return new Response('Зона не доступна на сервере');  
            }
        }
        else
        {
            return new Response('Неправильный формат домена');
        }
    }
    public function checkTransferDomainAction($domain_name)
    {
        $check_domain = $this->get('check_domain');

        $check_domain->init($domain_name);
        if ($check_domain->is_valid())
        {
            if ($check_domain->is_available_zone())
            {
                if ($check_domain->is_not_regOnServer())
                {
                    if ($check_domain->is_not_stopDomain())
                    {
                        if ($check_domain->is_available())
                        {
                            return new Response('true');
                        }
                        else
                        {
                            return new Response('Домен не существует');
                        }
                    }
                    else
                    {
                        return new Response('Домен содержится в списке стоп-доменов');
                    }
                }
                else
                {
                    return new Response('Домен уже зарегистрирован на сервере');
                }
            }
            else
            {
                return new Response('Зона не доступна на сервере');
                //return new Response($check_domain->get_tld());   
            }
        }
        else
        {
            return new Response('Неправильный формат домена');
        }
    }
    public function checkLoginAction($login)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $user_model = new UsersModel($em);
        if ($user_model->checkByLogin($login))
            return new Response('false');
        else
            return new Response('true');
    }
    public function checkEmailLoginAction($login)
    {
        if (preg_match("/[а-яА-Я]+/i", $login))
            return new Response('Некорректные символы');
        else
            return new Response('true');
    }
    public function generatePasswordAction()
    {
        $password = new GeneratePassword();
        return new Response($password->generatePassword(8, 2));
    }
}